<template>
  <div class="app-container">
    <div class="cardBox">
      <leftTree
        ref="leftTree"
        :data="treeData"
        node-key="id"
        :default-props="defaultProps"
        search-key="typeName"
        width="200px"
        :default-expand-keys="defaultExpandKeys"
        :defalut-expand-all="true"
        @handleNodeClickAll="handleNodeClick"
      />
      <el-col id="right-content" class="right-content" :offset="0" :span="18">
        <div class="box-title">
          <el-breadcrumb separator="/" style="line-height: 50px">
            <el-breadcrumb-item
              v-for="(item, index) in breadcrumb"
              :key="index"
              >{{ item }}</el-breadcrumb-item
            >
          </el-breadcrumb>
        </div>
        <div class="search-button">
          <div class="select-container">
            <el-select
              v-model="search.dataName"
              filterable
              placeholder="请选择数据类型"
              clearable
            >
              <el-option
                v-for="(item, key) in typesOptions"
                :key="key"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="search.industry"
              filterable
              placeholder="请选择行业"
              style="margin-left: 10px"
              clearable
            >
              <el-option
                v-for="(item, key) in industryOptions"
                :key="key"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </div>

          <div class="btnList">
            <el-button
              type="primary"
              icon="el-icon-chat-dot-square"
              @click="getAnswerInfo()"
              >生成内容</el-button
            >
            <el-button
              type="success"
              icon="el-icon-copy-document"
              @click="copyContent"
              >一键复制</el-button
            >
          </div>
        </div>
        <el-row>
          <div style="margin-top: 20px">
            <el-row>
              <div style="margin-top: 20px">
                <el-card>
                  <div class="scroll-container">
                    <el-skeleton v-if="loading" :loading="loading" animated>
                      <el-skeleton-item
                        v-for="n in 5"
                        :key="n"
                        style="margin-bottom: 20px"
                      >
                        <div style="height: 100%; width: 100%"></div>
                        <div
                          style="height: 14px; width: 80%; margin-top: 6px"
                        ></div>
                      </el-skeleton-item>
                    </el-skeleton>
                    <div
                      v-for="item in sortedData"
                      :key="item.sort"
                      class="article-section"
                    >
                      <h3>{{ item.sort + "、" + item.theme }}</h3>
                      <!-- 使用 p 标签并设置 white-space 属性 -->
                      <p style="white-space: pre">{{ item.answer }}</p>
                    </div>
                  </div>
                </el-card>
              </div>
            </el-row>
          </div>
        </el-row>
      </el-col>
    </div>
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import leftTree from "@/components/LeftTree";
import { mapGetters } from "vuex";
export default {
  components: {
    leftTree,
    Pagination,
  },
  data() {
    return {
      // 添加用于存储随机标题的属性
      randomLevelOneTitles: [],
      randomLevelTwoTitle: "",
      randomLevelThreeTitles: [],

      responseData: [],
      typesOptions: [],
      industryOptions: [],
      treeData: [],
      defaultProps: {
        children: "children",
        label: "typeName",
      },
      defaultExpandKeys: ["-1"],
      breadcrumb: ["星级上云"],
      loading: false,
      total: 0,
      search: {
        dataName: "",
        industry: "",
        keyword: "",
        treeStr: "-1",
      },
    };
  },
  computed: {
    ...mapGetters(["compInfo"]),
    sortedData() {
      // 确保 responseData.data 是一个数组，避免 undefined 或 null 的错误
      return Array.isArray(this.responseData)
        ? this.responseData.sort((a, b) => a.sort - b.sort)
        : [];
    },
  },
  created() {},
  mounted() {
    this.getTreeData();
    this.getIndustryOptions();
  },
  methods: {
    /**
     * @description: page
     * @param {*} page
     * @return {*}
     */
    async getAnswerInfo() {
      this.loading = true;
      const res = await this.$axios.post("/data/answer/search", this.search);
      if (this.search.treeStr == "-1") {
        this.loading = false;
        this.$message.error("请先选择星级和数据类型");
        return;
      }
      if (this.search.dataName == "") {
        this.loading = false;
        this.$message.error("请选择数据类型");
        return;
      }

      if (res.data.code === 200) {
        this.responseData = res.data.data;

        // 随机选择一级、二级和三级标题
        this.selectRandomTitles();

        // 遍历 responseData 并替换 answer 字段中的内容
        this.responseData.forEach((item, index) => {
          if (item.answer) {
            item.answer = this.replaceAnswer(item.answer, index);
          }
        });

        setTimeout(() => {
          this.loading = false;
        }, 100);
      } else {
        this.loading = false;
      }
    },

    async getDataName(id) {
      const res = await this.$axios.get("/data/answer/allDataName?id=" + id);
      if (res?.data.code === 200) {
        this.typesOptions = res.data.data;
      }
    },
    async getIndustryOptions(id) {
      const res = await this.$axios.get("/data/answer/allIndustry");
      if (res?.data.code === 200) {
        this.industryOptions = res.data.data;
      }
    },
    async getTreeData(page = 1) {
      this.search.current = page;
      const res = await this.$axios.get("/data/type/list");
      if (res?.data.code === 200) {
        this.treeData = [
          { id: "-1", typeName: "星级上云", children: res.data.data },
        ];
      }
    },
    async copyContent() {
      // 获取要复制的内容
      const contentToCopy = this.sortedData
        .map((item) => `${item.sort + "、" + item.theme}\n${item.answer}`)
        .join("\n\n");
      const el = document.createElement("textarea");
      el.value = contentToCopy;
      document.body.appendChild(el);
      el.select();

      try {
        const successful = document.execCommand("copy");
        if (successful) {
          this.$message.success("内容已复制到剪贴板");
        } else {
          this.$message.error("复制失败");
        }
        document.body.removeChild(el);
      } catch (err) {
        console.error("复制失败: ", err);
      }

      // try {
      //   // 使用Clipboard API复制文本
      //   await navigator.clipboard.writeText(contentToCopy);
      //   this.$message.success("内容已复制到剪贴板");
      // } catch (err) {
      //   console.error("复制失败", err);
      //   this.$message.error("复制失败");
      // }
    },
    /**
     * @description: 树节点点击
     * @param {*} data
     * @param {*} node
     * @return {*}
     */
    handleNodeClick({ data, node }) {
      this.breadcrumb = [];
      this.returnNodeLabel(node.parent);
      this.breadcrumb.push(data.typeName);
      this.search.treeStr = data.typeName === "星级上云" ? "-1" : data.id;
      this.getDataName(data.id);
      this.resetSearch();
    },
    /**
     * @description: 递归获取名称
     * @param {*} node
     * @return {*}
     */
    returnNodeLabel(node) {
      if (node.parent) {
        this.breadcrumb.unshift(node.data.typeName);
        this.returnNodeLabel(node.parent);
      }
    },
    /**
     * @description: 选中项
     * @param {*} val
     * @return {*}
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    /**
     * @description: 重置search
     * @param {*} formName
     * @return {*}
     */
    resetSearch() {
      this.search.dataName = "";
      this.search.industry = "";
      this.search.keyword = "";
      this.responseData = [];
    },
    selectRandomTitles() {
      // 一级标题，随机从两组中取一组
      const levelOneTitleOptions = [
        [
          "（1）",
          "（2）",
          "（3）",
          "（4）",
          "（5）",
          "（6）",
          "（7）",
          "（8）",
          "（9）",
          "（10）",
        ],
        ["1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9.", "10."],
      ];
      this.randomLevelOneTitles =
        levelOneTitleOptions[
          Math.floor(Math.random() * levelOneTitleOptions.length)
        ];
      // ➤	■	● ☆	✦	➜	➢ ▪️ ✪	✸ ❖	◼️ ◻️ ▲ ▼
      // 二级标题符号，随机选择
      const levelTwoTitleOptions = [
        "✦ ",
        "☆ ",
        "✪ ",
        "■ ",
        "✔ ",
        "➤ ",
        "❖ ",
        "➢ ",
      ];
      this.randomLevelTwoTitle =
        levelTwoTitleOptions[
          Math.floor(Math.random() * levelTwoTitleOptions.length)
        ];

      // 三级标题，随机从一组中取一组
      const levelThreeTitleOptions = [
        ["① ", "② ", "③ ", "④ ", "⑤ ", "⑥ ", "⑦ ", "⑧ ", "⑨ "],
        ["• ", "• ", "• ", "• ", "• ", "• ", "• ", "• ", "• "],
      ];
      this.randomLevelThreeTitles =
        levelThreeTitleOptions[
          Math.floor(Math.random() * levelThreeTitleOptions.length)
        ];
    },
    replaceAnswer(answer) {
      // 替换 {大写字母} 为随机选择的一级标题内容
      answer = answer.replace(/{([A-Z])}/g, (match, p1) => {
        const index = p1.charCodeAt(0) - 65; // 'A' 的 charCode 是 65
        return this.randomLevelOneTitles[index] || match; // 若超过数组长度则返回原值
      });

      // 替换 {数字} 为随机选择的二级标题符号
      answer = answer.replace(/{(\d+)}/g, () => this.randomLevelTwoTitle);

      // 替换 {小写字母} 为随机选择的三级标题内容
      answer = answer.replace(/{([a-z])}/g, (match, p1) => {
        const index = p1.charCodeAt(0) - 97; // 'a' 的 charCode 是 97
        return this.randomLevelThreeTitles[index] || match; // 若超过数组长度则返回原值
      });

      return answer;
    },
  },
};
</script>
<style lang="scss" scoped>
.search-button {
  line-height: 30px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  .el-input {
    width: 200px;
  }
}
.select-container {
  display: flex; /* 使用 flexbox 布局 */
}

.scroll-container {
  height: calc(70vh - 10px); /* 视口高度的60%，减去50px用于其他元素的高度 */
  max-height: 800px; /* 固定高度 */
  overflow-y: auto; /* 允许滚动 */
  padding: 10px;
  border: 1px solid #ccc;
}
.article-section {
  margin-bottom: 20px;
}
</style>
